package com.jeff.android.lab.jetpack.fragment

import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentPagerAdapter
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.setFragmentResultListener
import butterknife.BindView
import butterknife.OnClick
import com.jeff.android.lab.BaseFragment
import com.jeff.android.lab.R
import java.lang.String

/**
 * @author: dingfeng
 * @date: 2021/3/2
 * @since: 1.0.0
 **/
class FragmentA : BaseFragment() {

    @BindView(R.id.tv_data)
    lateinit var tvData: TextView

    @BindView(R.id.btn_send)
    lateinit var btnSend: Button

    @BindView(R.id.image_view)
    lateinit var mImageView: ImageView

    var launcherTakePicPreView: ActivityResultLauncher<Void>? = null

    override fun getRootLayout(): Int {
        return R.layout.jetpack_fragment_a
    }

    @OnClick(R.id.btn_send)
    fun sendData() {
        setFragmentResult("key_data_from_a",
                bundleOf("data" to "I am from a"))
    }

    @OnClick(R.id.btn_take_picture)
    fun takePicture() {
        launcherTakePicPreView?.launch(null)
    }

    override fun initView() {
        mImageView.visibility = View.VISIBLE

        setFragmentResultListener("key_data_from_b") {
            key, bundle -> tvData.text = String.format("接收数据:%s", bundle.getString("data"))
        }

        launcherTakePicPreView = registerForActivityResult(
                ActivityResultContracts.TakePicturePreview()
        ) { data: Bitmap? ->
            if (null != data) mImageView.setImageBitmap(data)
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setFragmentResult("key_data_from_a", bundleOf("data" to "I am from a onCreate"))
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }

}